package com.dai.zhenfujin.addresslist.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.dai.zhenfujin.AccountPasswordActivity;
import com.dai.zhenfujin.Constants.Constants;
import com.dai.zhenfujin.LoginActivity;
import com.dai.zhenfujin.MainActivity;
import com.dai.zhenfujin.R;
import com.dai.zhenfujin.bean.MessageEvent;
import com.dai.zhenfujin.db.Constant;
import com.dai.zhenfujin.db.InviteMessgeDao;
import com.dai.zhenfujin.message.ChatActivity;
import com.dai.zhenfujin.my.MyInfoActivity;
import com.dai.zhenfujin.utils.SPUtils;
import com.dai.zhenfujin.utils.UIUtils;
import com.daimajia.swipe.SwipeLayout;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMConversation.EMConversationType;
import com.hyphenate.easeui.model.EaseAtMessageHelper;
import com.hyphenate.easeui.model.EaseDingMessageHelper;
import com.hyphenate.easeui.widget.EaseTitleBar;
import com.hyphenate.util.NetUtils;

import org.greenrobot.eventbus.EventBus;

import static com.dai.zhenfujin.Constants.EventConstants.PUBLISH_DYNAMIC;

public class ConversationListFragment extends EaseConversationListFragment {

    private TextView errorText;
    private EaseTitleBar titleBar;

    @SuppressLint("ResourceAsColor")
    @Override
    protected void initView() {
        super.initView();
        View errorView = (LinearLayout) View.inflate(getActivity(), R.layout.em_chat_neterror_item, null);
        errorItemContainer.addView(errorView);
        errorText = (TextView) errorView.findViewById(R.id.tv_connect_errormsg);
        titleBar = (EaseTitleBar) getView().findViewById(R.id.title_bar);
        titleBar.setTitle("消息");
    }

    @Override
    protected void setUpView() {
        super.setUpView();
        // register context menu
        registerForContextMenu(conversationListView);
      /*  conversationListView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                EMConversation conversation = conversationListView.getItem(position);
                if (null ==conversation){
                    return;
                }
                String username = conversation.conversationId();
                SwipeLayout swipeLayout = view.findViewById(R.id.swipe_layout);
                swipeLayout.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(getActivity(), ChatActivity.class);
                        // it's single chat
                        intent.putExtra(Constant.EXTRA_USER_ID, username);
                        startActivity(intent);
                    }
                });

                if (username.equals(EMClient.getInstance().getCurrentUser()))
                    Toast.makeText(getActivity(), R.string.Cant_chat_with_yourself, Toast.LENGTH_SHORT).show();
                else {
                    // start chat acitivity
                    Intent intent = new Intent(getActivity(), ChatActivity.class);
                    // it's single chat
                    intent.putExtra(Constant.EXTRA_USER_ID, username);
                    startActivity(intent);
                }
            }
        });*/
      //  super.setUpView();
    }

    @Override
    protected void onConnectionDisconnected() {
        super.onConnectionDisconnected();
        if (NetUtils.hasNetwork(getActivity())) {
            errorText.setText(R.string.can_not_connect_chat_server_connection);
           // UIUtils.showToastSafe("连接不上服务器，请重新登录");
            if (!SPUtils.getBoolean(getContext(),"login")){
                  SPUtils.put(MainActivity.mContext, "welcome", true);
                 SPUtils.put(MainActivity.mContext, "login", false);
                 SPUtils.put(MainActivity.mContext, Constants.TOKEN, "");
                  Intent intent = new Intent(MainActivity.mContext, AccountPasswordActivity.class);
                  intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                 MainActivity.mContext.startActivity(intent);
                   MainActivity.mContext.finish();
            }else {
                EMClient.getInstance().logout(true);
                String phone = SPUtils.getString(getContext(), Constants.USER_MOBILE);
                EMClient.getInstance().login(phone, "zfj123", new EMCallBack() {//回调
                    @Override
                    public void onSuccess() {
                        EMClient.getInstance().chatManager().loadAllConversations();
                        //  SPUtils.put(getContext(), "login", true);
                        Log.d("main", "登录聊天服务器成功");
                    }

                    @Override
                    public void onProgress(int progress, String status) {

                    }

                    @Override
                    public void onError(int code, String message) {
                        if (200 == code) {
                            //  UIUtils.showToastSafe("用户已经登录");
                        } else {
                            //  UIUtils.showToastSafe("登录聊天服务器失败");
                        }
                        Log.d("main", "登录聊天服务器失败！");
                        Log.d("main", code + message);
                    }
                });
            }

          //  MessageEvent messageEventUpdateLabel = new MessageEvent();
          //  messageEventUpdateLabel.setMessageKey(PUBLISH_DYNAMIC);
           // EventBus.getDefault().post(messageEventUpdateLabel);

          //  MainActivity.mContext.finish();
        } else {
            errorText.setText(R.string.the_current_network);
        }
    }


    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
        //   getActivity().getMenuInflater().inflate(R.menu.em_delete_message, menu);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        boolean deleteMessage = false;
        EMConversation tobeDeleteCons = conversationListView.getItem(((AdapterContextMenuInfo) item.getMenuInfo()).position);
        if (tobeDeleteCons == null) {
            return true;
        }
        if (tobeDeleteCons.getType() == EMConversationType.GroupChat) {
            EaseAtMessageHelper.get().removeAtMeGroup(tobeDeleteCons.conversationId());
        }
        try {
            // delete conversation
            EMClient.getInstance().chatManager().deleteConversation(tobeDeleteCons.conversationId(), deleteMessage);
            InviteMessgeDao inviteMessgeDao = new InviteMessgeDao(getActivity());
            inviteMessgeDao.deleteMessage(tobeDeleteCons.conversationId());
            // To delete the native stored adked users in this conversation.
            if (deleteMessage) {
                EaseDingMessageHelper.get().delete(tobeDeleteCons);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        refresh();

        // update unread count
        //   ((MainActivity) getActivity()).updateUnreadLabel();
        return true;
    }
}
